#include "fpioa.h"
#include "sleep.h"
#include "gpio.h"
#include "sysctl.h"
#include "plic.h"
#include "timer.h"
/*****************************HARDWARE-PIN*********************************/
// 硬件IO口，与原理图对应
#define PIN_RGB_R             (12)
/*****************************SOFTWARE-GPIO********************************/
// 软件GPIO口，与程序对应
#define RGB_R_GPIONUM          (0)

/*****************************FUNC-GPIO************************************/
// GPIO口的功能，绑定到硬件IO口
#define FUNC_RGB_R             (FUNC_GPIO0 + RGB_R_GPIONUM)
uint32_t g_count;


void hardware_init(void)
{
    /* fpioa映射 */
    fpioa_set_function(PIN_RGB_R, FUNC_RGB_R);
}

int timer_timeout_cb(void *ctx) {
    uint32_t *tmp = (uint32_t *)(ctx);
    (*tmp)++;
    if ((*tmp)%2)
    {
        gpio_set_pin(RGB_R_GPIONUM,GPIO_PV_HIGH);

    }
    else
    {
        gpio_set_pin(RGB_R_GPIONUM,GPIO_PV_LOW);

    }
    return 0;
}

void init_timer(void) {
    /* 定时器初始化 */
    timer_init(TIMER_DEVICE_0);
    /* 设置定时器超时时间，单位为ns */
    timer_set_interval(TIMER_DEVICE_0, TIMER_CHANNEL_0, 500 * 1e6);
    /* 设置定时器中断回调 */
    timer_irq_register(TIMER_DEVICE_0, TIMER_CHANNEL_0, 0, 1, timer_timeout_cb, &g_count);
    /* 使能定时器 */
    timer_set_enable(TIMER_DEVICE_0, TIMER_CHANNEL_0, 1);
}


int main()
{
        /* 硬件引脚初始化 */
    hardware_init();

    /* 初始化系统中断并使能 */
    plic_init();
    sysctl_enable_irq();

    /* 初始化RGB灯 */
    gpio_set_drive_mode(RGB_R_GPIONUM, GPIO_DM_OUTPUT);
    gpio_set_pin(RGB_R_GPIONUM,GPIO_PV_HIGH);
    init_timer();

    while(1);
    return 0;

}